import {
    CreateOrUpdateHDPatrolTempInput, HDPatrolTempServiceProxy, HDPatrolTempEditDto, HDPatrolTitleEditDto,
    CreateOrUpdateHDPatrolTitleInput, HDPatrolTitleServiceProxy, HDPatrolFormListDto
} from './../../../../shared/service-proxies/service-proxies';
import { Component, EventEmitter, Injector, Input, OnInit, Output, SimpleChanges, OnChanges, ViewRef, ViewChild, TemplateRef } from '@angular/core';
import { CustomFormGroup, CustomFormItem, CustomFormListItem, itemType, Precondition } from '../custom-form.type';
import { AppComponentBase } from '../../../../shared/component-base/app-component-base';
import { HDPatrolFormServiceProxy, HDPatrolTempListDto } from '../../../../shared/service-proxies/service-proxies';
import { NzModalService, UploadChangeParam, UploadFile } from 'ng-zorro-antd';
import { AppConsts } from '../../../../abpPro/AppConsts';
import { TokenService } from 'abp-ng2-module/dist/src/auth/token.service';
import { PatrolTypeTreeComponent } from '@app/commmon/components/patrol-type-tree/patrol-type-tree.component';
@Component({
    selector: 'app-custom-form-editor-group',
    styleUrls: ['./custom-form-editor-group.component.less'],
    templateUrl: './custom-form-editor-group.component.html',

    styles: []
})
export class CustomFormEditorGroupComponent extends AppComponentBase implements OnInit, OnChanges {

    constructor(
        injector: Injector,
        private HDPatrolTemp: HDPatrolTempServiceProxy,
        private _hdPatrolTitleService: HDPatrolTitleServiceProxy,
        private _hDPatrolFormService: HDPatrolFormServiceProxy,
        private _modal: NzModalService
    ) {
        super(injector);
    }
    // static formJsonList: HDPatrolFormListDto[];
    @Input() isReadOnly = true;

    @Input() isPreview = false;

    @Input() formJson: CustomFormGroup = new CustomFormGroup();
    // @Input() selectedGroup: { group: CustomFormGroup, item: CustomFormItem };
    @Output() formJsonChange: EventEmitter<CustomFormGroup> = new EventEmitter<CustomFormGroup>();
    // @Output() selectedGroupChange: EventEmitter<{ group: CustomFormGroup, item: CustomFormItem }> = new EventEmitter<{ group: CustomFormGroup, item: CustomFormItem }>();
    @Input() isShowTool: false;

    @Input() toolBtns: { text: string, click: (formJson?: CustomFormGroup, event?: MouseEvent) => void }[] = [];

    @Input() index = '';

    @Input() precondition: Precondition[];
    @Output() preconditionChange: EventEmitter<Precondition[]> = new EventEmitter<Precondition[]>();

    isShowTypeModal = false;
    isVisibleTemplate = false;
    TitleisVisible = false;
    @Input() isEditor = true;
    entity: HDPatrolTempEditDto = new HDPatrolTempEditDto();
    ptentity: HDPatrolTitleEditDto = new HDPatrolTitleEditDto();
    currentGroup: any;
    patrolControlCode: string;
    patrolControl: string;
    titleJson: string;
    // formJsonList: HDPatrolFormListDto[] = CustomFormEditorGroupComponent.formJsonList;

    fileUploadUrl: string = AppConsts.remoteServiceBaseUrl + "/api/services/app/Attachment/UploadFile";
    fileUploadHeader: {
        Authorization: string
    };
    getFromListFilterText: string;
    patrolTypeId: number;
    importSelectModalIsVisible = false;
    importOption: { id: number; number: number; name: string; } = { id: undefined, number: undefined, name: undefined };
    importModel: 'form' | 'temp' = 'form';
    importModelSelect = false;
    selectTempId: number;
    formJsonString: string = JSON.stringify(this.formJson.toJson());
    @ViewChild('patroTypeTree', { static: true }) patroTypeTree: TemplateRef<null>;
    @ViewChild('importSelectModal', { static: true }) importSelectModal: TemplateRef<null>;
    ngOnChanges(changes: SimpleChanges): void {
        if ('formJson' in changes) {
            if (!changes.formJson.currentValue)
                this.formJson = new CustomFormGroup();
            else {
                this.formJsonString = JSON.stringify(changes.formJson.currentValue.toJson());
            }
        }
    }
    ngOnInit() {
        this.fileUploadHeader = { Authorization: "Bearer " + new TokenService().getToken() };
        this.formJson.setSelected(this.formJson);
        if (this.formJson.isImport && !this.isEditor) this.importGroup(this.formJson);
    }
    reset() {
        this.formJson = CustomFormGroup.fromJson(JSON.parse(this.formJsonString));
    }
    selectGroup(e: MouseEvent) {
        e.stopPropagation();
        this.formJson.root.setSelected(this.formJson);
    }
    getKeyStr(key: number) {
        return ''; // Number((key + '').substr((key + '').length - 3));
    }
    /**
    * 通过id查询表单
    */
    async getGroupById(id: number): Promise<CustomFormGroup> {
        return new Promise(res => {
            this._hDPatrolFormService.getForEdit(id).subscribe(result => {
                res(result.hdPatrolForm.formJson ? CustomFormGroup.fromJson(JSON.parse(result.hdPatrolForm.formJson), this.formJson.root) : undefined);
            });
        });
    }

    /**
     * 上传文件并获得路径
     */
    async fileUopdate(): Promise<string> {
        return '';
    }

    onCheckBoxChange(item: CustomFormItem) {
        setTimeout(() => {
            if (item.maxSelected <= item.options.filter(v => v.checked).length) {
                item.options.forEach(v => v.disable = !v.checked);
            } else {
                item.options.forEach(v => v.disable = false);
            }
        }, 0);
    }
    fileUploadBefor = () => {
        if (this.isEditor) return false;
        else return true;
    }
    fileUploadChange(fc: UploadChangeParam, item: CustomFormItem) {
        switch (fc.file.status) {
            case "done": // 上传完成
                // 获取服务端返回的信息
                if (fc.file.response.success) {
                    item.files.push(fc.file.response.result);
                }
                break;
            case "error": // 上传错误
                abp.message.error(this.l("UploadFailed"));
                break;
        }
    }
    /**
     * 导入 组
     */
    async importGroup(item: CustomFormGroup) {
        if (!item.isImport || !item.importOption || !item.importOption.id) return;
        item.itemList.splice(0, item.itemList.length);
        this.getGroupById(item.importOption.id).then(v => {
            if (!v) return;
            const list: CustomFormListItem[] = [];
            if (item.importOption.number)
                for (let i = 0; i < item.importOption.number; i++) {
                    if (v.itemList.length === 0) break;
                    list.push(...v.itemList.splice(Math.floor(Math.random() * v.itemList.length), 1));
                }
            else list.push(...v.itemList);
            list.forEach(i => {
                item.pushListItem(new CustomFormListItem(i.group || i.item));
            });
            return list;
        });
    }
    previewForm(item: HDPatrolFormListDto, e: MouseEvent) {
        e.stopPropagation();
        this._hDPatrolFormService.getForEdit(item.id).subscribe(result => {
            this.modalHelper.static(CustomFormEditorGroupComponent, {
                formJson: CustomFormGroup.fromJson(JSON.parse(result.hdPatrolForm.formJson)),
                isEditor: false
            }).subscribe(() => { });
        });
    }
    // 选择导入的模块
    selectImportGroup(importOption: { id: number; number: number; name: string; }) {
        this.importOption = importOption;
        // this.importSelectModalIsVisible = true;
        const modal = this._modal.create({
            nzTitle: this.l('Select Import'), nzOnOk: () => {
                this.selectImportGroupOnOk();
                modal.close();
            },
            nzContent: this.importSelectModal
        });
    }
    selectImportGroupOnOk() {
        if (this.importOption.id && this.importModel === 'form') {
            this.selectCallback(this.importOption.id);
        }

        if (this.importModel === 'temp') {
            this.selectCallback(this.selectTempId);
        }

        this.importSelectModalIsVisible = false;
        this.importOption = { id: undefined, name: undefined, number: undefined };
    }
    selectCallback = (id: number) => { };
    /**
     * 打开添加组件的弹窗
     */
    addListItem() {
        this.isShowTypeModal = true;
    }
    /**
     * 计算总分
     */
    getScoreCount(item: CustomFormGroup | CustomFormItem): number {
        let score = 0;
        if (item.isGroup) {
            score = score + this.getScoreCount(item);
        } else if (item.isGroup === false) {
            item.options.forEach(v => {
                score += v.score || 0;
            });
        }
        return score;
    }
    addImport(impType: 'dynamic-import' | 'replace-import') {
        if (impType === 'dynamic-import') {
            this.importModelSelect = false;
            this.importModel = 'form';
            // if (CustomFormEditorGroupComponent.formJsonList === undefined || CustomFormEditorGroupComponent.formJsonList.length === 0) this.getFormJsonList();
            const group = new CustomFormGroup('未命名分组');
            group.isImport = true;
            group.importOption = { number: undefined, id: undefined, name: undefined };
            group.root = this.formJson.root;
            this.formJson.pushListItem(new CustomFormListItem(group));
            this.isShowTypeModal = false;
        } else if (impType === 'replace-import') {
            const modal = this._modal.create({
                nzTitle: this.l('Select Import'), nzOnOk: () => {
                    this.selectImportGroupOnOk();
                    modal.close();
                },
                nzContent: this.importSelectModal
            });
            this.importModelSelect = true;
            this.selectCallback = (id: number) => {
                if (this.importModel === 'form') {
                    this.getGroupById(id).then(v => {
                        if (!v) return;
                        v.root = this.formJson.root;
                        v.key = this.formJson.key;
                        this.formJson = v;
                    });
                } else if (this.importModel === 'temp') {
                    this.HDPatrolTemp.getForEdit(id).subscribe(res => {
                        const group = CustomFormGroup.fromJson(JSON.parse(res.hdPatrolTemp.formjson));
                        group.root = this.formJson.root;
                        group.key = this.formJson.key;
                        if (group.groupName === 'default')
                            this.formJson = group;
                        else {
                            this.formJson.itemList.splice(0, this.formJson.itemList.length);
                            this.formJson.pushListItem(new CustomFormListItem(group));
                        }
                    });
                }
            };
            this.isShowTypeModal = false;
        }
    }
    addItem(type: itemType) {
        this.formJson.addItem(type);
        this.isShowTypeModal = false;
        this.formJson.root.selectedGroup = this.formJson;
    }
    addGroup() {
        this.formJson.addGroup('未命名分组');
        this.isShowTypeModal = false;
        this.formJson.root.selectedGroup = this.formJson;
    }

    removeItem(key) {
        this.formJson.root.removeItem(key, this.formJson);
    }
    /**
     * 保存为模板
     */
    saveforTemplete(group: CustomFormGroup) {
        this.currentGroup = group.toJson();
        this.isVisibleTemplate = true;
    }

    handleOk() {
        const temp = new CreateOrUpdateHDPatrolTempInput();
        temp.hdPatrolTemp.name = this.entity.name;
        if (this.currentGroup) temp.hdPatrolTemp.formjson = JSON.stringify(this.currentGroup);
        this.HDPatrolTemp.createOrUpdate(temp).subscribe(() => {
            this.notify.success(this.l('SavedSuccessfully'));
            this.isVisibleTemplate = false;
        });
    }
    /**
     * 存为题目
     */
    SaveAsTitle(item: CustomFormItem) {
        this.titleJson = JSON.stringify(item.toJson());
        const modal = this._modal.create({
            nzTitle: this.l('Save as subject'), nzOnOk: () => {
                this.TitleOk();
                modal.close();
            }, nzContent: this.patroTypeTree
        });
    }
    TitleOk() {
        const input = new CreateOrUpdateHDPatrolTitleInput();
        input.hdPatrolTitle.hdPatrolTypeId = this.ptentity.hdPatrolTypeId;
        input.hdPatrolTitle.patrolType = this.ptentity.patrolType;
        input.hdPatrolTitle.titleJson = this.titleJson;
        input.hdPatrolTitle.patrolControl = this.patrolControl;
        input.hdPatrolTitle.patrolControlCode = this.patrolControlCode;
        this._hdPatrolTitleService.createOrUpdate(input).subscribe(res => {
            this.notify.success(this.l('SavedSuccessfully'));
            this.TitleisVisible = false;
        });
    }
    scrollIntoItemByKey(key: string) {
        const ele = document.getElementById(key);
        if (!ele) return;
        setTimeout(() => {
            ele.scrollIntoView({ behavior: "smooth", block: "start", inline: "nearest" });
        }, 0);
    }
}
